import Taro, { Component } from '@tarojs/taro'
import { View, Block, Text, Image, Button } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import { user, usered } from '../../actions/counter'
import allExtrance from './../../config/allExtrance'
import { getGlobalData } from './../../config/global_data'
import allRequest from './../../api/allRequest'
import './consumerJobList.less'
import { MoreFormid } from './../index'

let _this;

@connect(({ counter }) => ({
    counter
}), (dispatch) => ({
    usered() {
        dispatch(usered())
    },
    user() {
        dispatch(user())
    },
}))
class ConsumerJobList extends Component {

    constructor(props) {
        super(props)
        this.state = {
            position: {},
            salary_unit: ['', '元/月', '元/日', '元/时'],
            educationArr: ['学历不限', '小学', '初中', '中专', '高中', '大学专科', '大学本科', '硕士', '博士', '博士后', '其它'],
            tagArr: [],
            type: '',
            applySuccess: false,
            resumeAlert: false,
            complete: '0%'
        }
    }

    componentWillReceiveProps(nextProps) {
        console.log(this.props, nextProps)
    }

    componentDidMount() {
        _this = this
        let { jobs, type } = this.props;
        this.setState({ jobs, type })

        if (!Taro.getStorageSync('tag')) {
            allRequest.tag()
                .then(res => {
                    let { tagArr } = this.state
                    for (let i in res) {
                        if (i != '__info') {
                            tagArr.push(res[i])
                        }
                    }
                    allExtrance.util.Taro.setStorageSync('tag', tagArr)
                    this.setState({ tagArr })
                })
                .catch(err => console.log(err))
        } else {
            this.setState({
                tagArr: JSON.parse(Taro.getStorageSync('tag'))
            })
        }
    }

    componentWillUnmount() { }

    componentDidShow() { }

    componentDidHide() { }

    transDate(str = '') {
        str = str.split('-');
        return str[1] + '月' + str[2].split(' ')[0] + '日';
    }

    //省市区截取
    getArea(str) {
        let area = {}
        let index11 = 0
        let index1 = str.indexOf("省")
        if (index1 == -1) {
            index11 = str.indexOf("自治区")
            if (index11 != -1) {
                area.Province = str.substring(0, index11 + 3)
            } else {
                area.Province = str.substring(0, 0)
            }
        } else {
            area.Province = str.substring(0, index1 + 1)
        }

        let index2 = str.indexOf("市")
        if (index11 == -1) {
            area.City = str.substring(index11 + 1, index2 + 1)
        } else {
            if (index11 == 0) {
                area.City = str.substring(index1 + 1, index2 + 1)
            } else {
                area.City = str.substring(index11 + 3, index2 + 1)
            }
        }

        let index3 = str.lastIndexOf("区")
        if (index3 == -1) {
            index3 = str.indexOf("县")
            area.Country = str.substring(index2 + 1, index3 + 1)
        } else {
            area.Country = str.substring(index2 + 1, index3 + 1)
        }
        return area;
    }

    toNavigator(url, e) {
        e.stopPropagation()
        // allRequest.wokerMe()
        //     .then(res => {
        //         if (res) {
        //             if (Taro.getEnv() === Taro.ENV_TYPE.WEAPP) {
        //                 if (Taro.getStorageSync("hasWechatUser")) {
        //                     Taro.navigateTo({
        //                         url: url
        //                     })
        //                     _this.props.user()
        //                 } else {
        //                     _this.props.usered()
        //                 }
        //             } else {
        //                 Taro.navigateTo({
        //                     url: url
        //                 })
        //             }
        //         }
        //     })
        //     .catch(err => { console.log(err) })
        Taro.navigateTo({
            url: url
        })
    }

    hasWechatUser() {
        _this.props.user()
    }

    cancelCollect(job_id, e) {
        allRequest.star({ job_id, action: 0, 'worker_demand_id': getGlobalData('worker_demand_id') })
            .then(res => {
                allExtrance.util.Taro.showToast('取消收藏成功')
                setTimeout(() => {
                    this.props.onRefresh()
                }, 1000)
            })
            .catch(err => { console.log(err) })
    }

    communityModal(type, e) {
        _this.setState(preState => ({ [type]: !preState[type] }))
    }

    postResume(job_id, e) {
        this.setState({ chooseJobId: job_id })
        allRequest.wokerMe()
            .then(res => {
                if (res) {
                    if (res.complete == '0%') {
                        this.setState({ resumeAlert: true, complete: res.complete })
                    } else {
                        allRequest.jobApply({ job_id })
                            .then(result => {
                                if (result) {
                                    let {jobs} = this.props
                                    for(let i = 0;i < jobs.length;i++){
                                        if(jobs[i].job_id == job_id){
                                            jobs[i].apply = true
                                        }
                                    }
                                    this.setState({
                                        applySuccess: true
                                    })
                                } else {
                                    allExtrance.util.Taro.showToast('网络不稳，稍后重试')
                                }

                            })
                            .catch(err => { console.log(err) })
                    }
                }
            })
            .catch(err => { console.log(err) })
    }

    editResume(e) {
        this.setState({ resumeAlert: false }, () => {
            Taro.navigateTo({
                url: '/subPackages/subPackageS/myResume/myResume'
            })
        })
    }
    keepApply(e) {
        this.setState({ resumeAlert: false }, () => {
            allRequest.jobApply({ "job_id": this.state.chooseJobId })
                .then(result => {
                    if (result) {
                        this.setState({
                            applySuccess: true
                        })
                    } else {
                        allExtrance.util.Taro.showToast('网络不稳，稍后重试')
                    }

                })
                .catch(err => { console.log(err) })
        })
    }

    stopPropagation(e) {
        e.stopPropagation()
    }


    render() {
        let { jobs } = this.props
        let { type, salary_unit, educationArr, tagArr, applySuccess, resumeAlert, complete } = this.state
        console.log(jobs)
        return (
            <View className='consumerJobList'>
                <View className='job-list my-class' >
                    {/* <btn type='wrapper'> */}
                    {
                        jobs && jobs.length > 0 && jobs.map((item, index) => <Block>
                            <View className={`job-cell ${item.disable && 'disable'}`} hover-class='none'>
                                {/* <!-- 投递记录 --> */}
                                {/* {
                                    type === 'post' && <Block>
                                        <View className='row row-0'>
                                            <View className='post-time'>{this.transDate(item.time_create)}投递</View>
                                            {item.apply_status == 1 && <View className='status'>待查看</View>}
                                            {item.apply_status == 2 && <View className='status'>已查看</View>}
                                        </View>
                                    </Block>
                                } */}

                                {/* <!-- 职位收藏 --> */}
                                {/* {
                                    type === 'collect' && <Block>
                                        <View className='row row-0'>
                                            <View className='collect-time'>{this.transDate(item.time_create)}收藏</View>
                                        </View>
                                    </Block>
                                } */}
                                <MoreFormid>
                                    <View className='content' onClick={this.toNavigator.bind(this, `/subPackages/subPackageS/jobInfo/jobInfo?companyJobId=${item.job_id}`)} >
                                        <View className='row row-1'>
                                            <View className='position-name'>
                                                <View>{item.job_title || item.position.position_title}</View>
                                                {item.time_toplist > 0 && <View className='zhiding'><View style='margin-top:1.5px'>置顶</View></View>}
                                            </View>
                                            {
                                                item.salary_unit == 4 ? (<View className='salary'>
                                                    <View className='num'>面议</View>
                                                </View>) : (item.salary_min ? <View className='salary'>
                                                    <View className='num'>{item.salary_min === item.salary_max ? item.salary_min : item.salary_min + '-' + item.salary_max}</View>
                                                    <View className='unit' style={`${Taro.getEnv() === Taro.ENV_TYPE.WEAPP ? 'margin-bottom:2px' : 'margin-bottom:-2px'}`}>{salary_unit[item.salary_unit]}</View>
                                                </View> :
                                                    <View className='salary'>
                                                        <View className='num'>{item.salary}</View>
                                                    </View>)
                                            }
                                        </View>
                                        <View className='row row-2'>
                                            <View className='poi-name'>{item.company.title}</View>
                                            {item.distanceStr && <View className='distance-str'>{item.distanceStr}</View>}
                                        </View>
                                        <View className='row row-3'>
                                            <View className='condition'>
                                                {/* {this.getArea(item.company.address).Country != '' && <View className='item'>{item.company.address ? this.getArea(item.company.address).Country : this.getArea(item.address).Country}</View>} */}
                                                {/* {this.getArea(item.company.address).Country != '' && <View style='width:1px;background:#666;height:8px'></View>} */}
                                                {item.area_name && <View className='item'>{item.area_name}</View>}
                                                {item.area_name && Taro.getEnv() === Taro.ENV_TYPE.WEAPP && <View style='width:1px;background:#999;height:8px'></View>}
                                                <View className='item'>{educationArr[Number(item.job_education)]}</View>
                                                {Taro.getEnv() === Taro.ENV_TYPE.WEAPP && <View style='width:1px;background:#999;height:8px'></View>}
                                                {item.job_experience_min == item.job_experience_max && item.job_experience_max == 0 && <View className='item'>经验不限</View>}
                                                {item.job_experience_min == item.job_experience_max && item.job_experience_max != 0 && <View className='item'>{item.job_experience_max + '年'}</View>}
                                                {item.job_experience_min != item.job_experience_max && <View className='item'>{item.job_experience_min + '-' + item.job_experience_max}年</View>}
                                            </View>
                                            {/* {item.distanceStr && <View className='distance-str'>{item.distanceStr}</View>} */}
                                            <View className='public-time'>{this.transDate(item.time_update)}</View>
                                        </View>
                                        <View className='row row-4'>
                                            {
                                                (item.tag && item.tag.length > 0) ?
                                                    <View className='welfares'>
                                                        {
                                                            item.tag.map((tag, index) => <Block>
                                                                {index < 4 && <View className='item' style={`color:${Taro.getStorageSync('welfareColor')};border:1px solid ${Taro.getStorageSync('welfareColor')}`}>{tagArr[Number(tag.tag_type) - 1]}</View>}
                                                            </Block>)
                                                        }
                                                    </View> : <View className='welfares'></View>
                                            }
                                            {/* <View className='public-time'>{this.transDate(item.time_create)}</View> */}
                                        </View>
                                        {
                                            type !== 'post' && type !== 'collect' && item.sell_status === 2 && item.resume_price != 0 && <Block>
                                                <View className='recommand_con dis-flex flex-left flex-middle'>
                                                    <Text className='recommand_con_text'>推荐好友，得赏金</Text>
                                                    <Image className='recommand_con_img' mode='aspectFit' src='https://file.open.banchengyun.com/2019/01/21/154803671665696.png' />
                                                    <Text className='recommand_con_text'>简历合适{item.resume_price}元</Text>
                                                </View>
                                            </Block>
                                        }

                                        {/* <!-- 失效图标 --> */}
                                        {/* {item.company_status && <Image className='icon-disable' src='https://file.open.banchengyun.com/2019/04/19/155566395058524.png' />} */}
                                    </View>
                                </MoreFormid>
                                {
                                    (type === 'post' || type === 'collect') && <View className='actionBlock'>
                                        {type === 'post' && <View className='time_create'>{this.transDate(item.time_create)}投递</View>}
                                        {type === 'collect' && <View className='time_create'>{this.transDate(item.time_create)}收藏</View>}
                                        {type === 'collect' && <View className='actionBtnBlock'>
                                            <View className='actionBtn cancel' onClick={this.cancelCollect.bind(this, item.job_id)}>取消收藏</View>
                                            {
                                                !item.apply
                                                    ? <View className='actionBtn confirm' onClick={this.postResume.bind(this, item.job_id)} style={`background-color:${Taro.getStorageSync('baseColor')}`}>投递简历</View>
                                                    : <View className='actionBtn confirm' style='background:#cccccc'>已投递</View>
                                            }
                                        </View>}
                                        {type === 'post' && <View className='acitonCon'>{item.apply_status == 1 ? '待查看' : '已查看'}</View>}
                                    </View>
                                }
                            </View>
                        </Block>
                        )
                    }
                    {/* <View style='width:100%;height:49px'></View> */}
                    {/* </btn> */}
                </View>

                {
                    applySuccess && <View className='zhezhao' onClick={this.communityModal.bind(this, 'applySuccess')}>
                        <View className='messageBlock' onClick={this.stopPropagation.bind(this)}>
                            <View className='themeColor' style={`background:${Taro.getStorageSync('baseColor')};height:135px`}>
                                <View className='logoImg logoImgTwo' style={`background-color:${Taro.getStorageSync('baseColor')};z-index:-1`}>
                                    <Image src='https://file.open.banchengyun.com/353/36268ed201fc8eb3658f5b2f67e9ae25'></Image>
                                </View>
                                <View className='cloud'>
                                    <Image src='https://file.open.banchengyun.com/2019/06/25/156145781925397.png' />
                                </View>
                            </View>
                            <View className='msgContent'>
                                <View className='msgTitle' style='font-weight:bold'>投递成功</View>
                                <View className='msgRow'>恭喜简历投递成功！</View>
                                <View className='msgRow' style='margin-bottom:25px'>坐等好消息吧~</View>
                            </View>
                            <View className='msgClose' onClick={this.communityModal.bind(this, 'applySuccess')}>
                                <Image src='https://file.open.banchengyun.com/2019/06/25/156145781914338.png'></Image>
                            </View>
                        </View>
                    </View>
                }
                {
                    resumeAlert && <View className='zhezhao' onClick={this.communityModal.bind(this, 'resumeAlert')}>
                        <View className='messageBlock' onClick={this.stopPropagation.bind(this)}>
                            <View className='themeColor' style={`background-color:${Taro.getStorageSync('baseColor')};height:105px`}>
                                <View className='logoImg logoImgThird'>
                                    <Image src='https://file.open.banchengyun.com/353/5bafe0d28322d67ab7b4e468ac9e2a5b'></Image>
                                </View>
                                <View className='cloud'>
                                    <Image src='https://file.open.banchengyun.com/2019/06/25/156145781925397.png' />
                                </View>
                            </View>
                            <View className='msgContent'>
                                <View className='msgTitle' style='font-weight:bold'>简历不完善</View>
                                <View className='msgRow'>您的简历信息过于简单</View>
                                <View className='msgRow'>完善简历信息提高面试成功率哦~</View>
                                {complete == '0%' && <Button className='msgBtn' onClick={this.editResume.bind(this)} style={`background-color:${Taro.getStorageSync('baseColor')}`}>完善简历</Button>}
                                {
                                    (parseFloat(complete) > parseFloat('0%'))
                                    && <View className='btnBlock'>
                                        <Button className='whiteBtn' onClick={this.keepApply.bind(this)}>继续投递</Button>
                                        <Button className='themeBtn' onClick={this.editResume.bind(this)} style={`background-color:${Taro.getStorageSync('baseColor')}`}>完善简历</Button>
                                    </View>
                                }

                            </View>
                            <View className='msgClose' onClick={this.communityModal.bind(this, 'resumeAlert')}>
                                <Image src='https://file.open.banchengyun.com/2019/06/25/156145781914338.png'></Image>
                            </View>
                        </View>
                    </View>
                }
            </View>
        )
    }
}

export default ConsumerJobList
